<?php

namespace app\common\controller;

use think\Addons;
use app\common\library\Menu;
use app\admin\model\AuthRule;
use think\Db;
use think\Exception;

/**
 * 后台控制器基类
 */
class Addoninstall extends Addons
{
	//安装默认字段
	protected function installdb($addonName, $addonPath){
		$db_file = $addonPath.'/database.php';
		if(!is_file($db_file))return false;
				
		$typefield = \app\common\model\Config::getTypeField();
		
		$tablefield = include $db_file;
		$customtable = [];
		foreach($tablefield as $k => $v){
			if(isset($v['custom']) && $v['custom']){
				$customtable[$k] = $v['field'];	
			}
			if(!empty($v['sql'])){
				if(!is_array($v['sql']))$v['sql'] = [$v['sql']];
				foreach($v['sql'] as $vv){
                	$vv = str_ireplace('__PREFIX__', config('database.prefix'), $vv);
                	$vv = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $vv);
					Db::execute($vv);
				}
			}
			if(!empty($v['field'])){
				$sql = "
					CREATE TABLE IF NOT EXISTS `".config('database.prefix').$k."` (
					  `id` int(11) NOT NULL AUTO_INCREMENT,
					  PRIMARY KEY (`id`)
					) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='".$v['title']."';
				";
				Db::execute($sql);
				//创建字段
				foreach($v['field'] as $kk => $vv){
					if($vv['name'] && $vv['title'] && $vv['type']){
						if(!$vv['value'])$vv['value'] = $typefield[$vv['type']][1];
						try{
							Db::execute("ALTER TABLE ".\think\Config::get('database.prefix').$k." ADD `".$vv['name']."` ".$typefield[$vv['type']][0]." NOT NULL DEFAULT '".$vv['value']."' COMMENT '".$vv['title']."'");
						}catch(Exception $e1){
							//存在则修改
							try{
								Db::execute("ALTER TABLE ".\think\Config::get('database.prefix').$k." CHANGE `".$vv['name']."` `".$vv['name']."` ".$typefield[$vv['type']][0]." NOT NULL DEFAULT '".$vv['value']."' COMMENT '".$vv['title']."'");
							}catch(Exception $e2){
								//修改失败保持原状
							}
						}
					}
				}
			}
		}
		$configModel = \fast\Addon::getConfigModel($addonName);
		if($configModel)$configModel->get(1)->save(['customtable' => $customtable]);
		//生成字段索引或约束
		//ALTER TABLE zt_action DROP INDEX `id`;
		//ALTER TABLE zt_action ADD UNIQUE  `id` (  `id` ) COMMENT  '';
		//ALTER TABLE zt_action ADD INDEX  `id` (  `id` ) COMMENT  '';
		foreach($tablefield as $k => $v){
			if(empty($v['field']))continue;
			foreach($v['field'] as $kk => $vv){
				if($vv['name'] && $vv['title'] && $vv['type']){
					if(!empty($vv['key'])){
						try{
							$keyname = '`'.str_replace(',', '_', $vv['key']).'`';
							$keyfield = '`'.str_replace(',', '`,`', $vv['key']).'`';
							Db::execute("ALTER TABLE ".\think\Config::get('database.prefix').$k." ADD INDEX $keyname ($keyfield)");
						}catch(Exception $e){
						}
					}
					if(!empty($vv['unique'])){
						try{
							$uniquename = '`'.str_replace(',', '_', $vv['unique']).'`';
							$uniquefield = '`'.str_replace(',', '`,`', $vv['unique']).'`';
							Db::execute("ALTER TABLE ".\think\Config::get('database.prefix').$k." ADD UNIQUE $uniquename ($uniquefield)");
						}catch(Exception $e){
						}
					}
				}
			}
		}

		return true;
	}
	
	protected function uninstalldb($addonName, $addonPath){
		$db_file = $addonPath.'/database.php';
		if(!is_file($db_file))return false;
		$tablefield = include $db_file;
		foreach($tablefield as $k => $v){
			if(isset($v['uninstall']) && $v['uninstall']){
				Db::execute("DROP TABLE IF EXISTS `".config('database.prefix').$k."`;");
			}
		}
	}

	 /**
     * 导入SQL
     * 
     * @param   string    $name   插件名称
     * @param   string    $file   sql文件名
     * @return  boolean
     */
    public function importsql($file = 'install.sql')
    {
        $sqlFile = dirname(__FILE__) . '/'. $file;
        if (is_file($sqlFile))
        {
            $lines = file($sqlFile);
            $templine = '';
            foreach ($lines as $line)
            {
                if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*')
                    continue;

                $templine .= $line;
                if (substr(trim($line), -1, 1) == ';')
                {
                    $templine = str_ireplace('__PREFIX__', config('database.prefix'), $templine);
                    $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);
                    try
                    {
                        Db::getPdo()->exec($templine);
                    }
                    catch (\PDOException $e)
                    {
                        //$e->getMessage();
                    }
                    $templine = '';
                }
            }
        }
        return true;
    }
	
    public function install()
    {
        return true;
    }

    public function uninstall()
    {
        return true;
    }
}